<?php

class IndexController extends Controller
{

    public $layout = '//layouts/main';
    private $google_service;
    private $google_client;
    public $application_name;
    public $client_id;
    public $client_secret;
    public $redirect_uri;
    public $developer_key;
    public $access_type;

    public function actionIndex()
    {
//        $dataProvider = Gadata::model()->getDataProvider();
//        $graphData = Gadata::model()->getReportData();
//        $this->render('index', array(
//            'dataProvider' => $dataProvider,
//            'graphData' => $graphData
//        ));

        $top30pages = Gadata::model()->getTop30ByPageviews();
        $topPages = array();

        foreach ($top30pages as $record) {
            $topPages[] = $record->landing_page;
        }

        $topPrev30Pages = Gadata::model()->getPreviousTop30Landingpage($topPages);

        for ($i = 0; $i < 30; $i++) {
            $origin = $top30pages[$i];
            for ($j = 0; $j < sizeof($topPrev30Pages); $j++) {
                $prev = $topPrev30Pages[$j];
                if ($origin->landing_page == $prev->landing_page) {
                    if ($origin->rank > $prev->rank) {
                        $origin->up_status = -1; // tụt hạng
                    } else if ($origin->rank == $prev->rank) {
                        $origin->up_status = 0;
                    } else {
                        $origin->up_status = 1; // tăng hạng
                    }
                    $origin->margin = $prev->rank - $origin->rank;
                }
            }
        }
        $this->render('index', array(
            'top30pages' => $top30pages,
            'topPrev30Pages' => $topPrev30Pages
        ));
    }

    public function actionHistory()
    {
        $landing_page = Yii::app()->getRequest()->getQuery('landing_page');
        $page_title = Yii::app()->getRequest()->getQuery('page_title');
        $decode_landing_page = base64_decode($landing_page);
        $decode_page_title = base64_decode($page_title);
        $result = Gadata::model()->getHistoryByPage($decode_landing_page, $decode_page_title);

        for ($i = count($result) - 2; $i > 1; $i--) {
            if (intval($result[$i]->rank) > intval($result[$i + 1]->rank)) {
                $result[$i]->up_status = -1;
            } else if (intval($result[$i]->rank) == intval($result[$i + 1]->rank)) {
                $result[$i]->up_status = 0;
            } else {
                $result[$i]->up_status = 1;
            }
        }
        $this->render('history', array(
            'landing_pages' => $result,
        ));
    }

    public function actionTop30()
    {
        $top30pages = Gadata::model()->getTop30ByPageviews();
        $topPages = array();

        foreach ($top30pages as $record) {
            $topPages[] = $record->landing_page;
        }

        $topPrev30Pages = Gadata::model()->getPreviousTop30Landingpage($topPages);

        for ($i = 0; $i < 30; $i++) {
            $origin = $top30pages[$i];
            for ($j = 0; $j < sizeof($topPrev30Pages); $j++) {
                $prev = $topPrev30Pages[$j];
                if ($origin->landing_page == $prev->landing_page) {
                    if ($i > $j) {
                        $origin->up_status = 1;
                    } else if ($i == $j) {
                        $origin->up_status = 0;
                    } else {
                        $origin->up_status = -1;
                    }
                }
            }
        }
        $this->render('top30', array(
            'top30pages' => $top30pages,
            'topPrev30Pages' => $topPrev30Pages
        ));
    }

    public function actionTreemap()
    {
        $this->render('treemap');
    }

    public function actionJsonData()
    {
        header('Content-Type: application/json');
        $json = Gadata::model()->getVisualizeJson();
        echo $json;
    }

    public function actionNotProvided()
    {
        $criteria = new CDbCriteria();
        $criteria->distinct = true;

        $dataProvider = new CActiveDataProvider('Notprovided', array(
                    'criteria' => $criteria
                ));
        $this->render('notprovided', array(
            'dataProvider' => $dataProvider
        ));
    }

    public function actionRelatedKeyword()
    {
        $landing_page = Yii::app()->getRequest()->getQuery('landing_page');
        $notprovided = Notprovided::model()->find('landing_page="' . base64_decode($landing_page) . '"');

        $criteria = new CDbCriteria();
        $criteria->condition = 'notprovided_id=' . $notprovided->id;

        $related_keywords = $dataProvider = new CActiveDataProvider('RelatedKeywords', array(
                    'criteria' => $criteria
                ));
        if (!sizeof($related_keywords->getData())) {
            Yii::import('ext.googleapi.Google_Client', true);
            $this->getGoogleService();
            $data = $this->getData($landing_page);
            $rows = $data['rows'];
            foreach ($rows as $row) {
                $keyword = new RelatedKeywords;
                $keyword->notprovided_id = $notprovided->id;
                $keyword->keywords = $row[0];
                $keyword->save();
            }

            $criteria->condition = 'notprovided_id=' . $notprovided->id;

            $related_keywords = $dataProvider = new CActiveDataProvider('RelatedKeywords', array(
                        'criteria' => $criteria
                    ));
        }
        $this->render('keyword', array(
            'dataProvider' => $related_keywords,
            'landing_page' =>  base64_decode($landing_page),
        ));
    }

    public function getGoogleClient()
    {
        Yii::import('ext.googleapi.Google_Client', true);

//        $this->application_name = 'Reader Happiness Indicator';
//        $this->client_id = '108350372048.apps.googleusercontent.com';
//        $this->client_secret = 'zh7QvzhRFSG8GSvlvd2RDIdn';
//        $this->redirect_uri = 'http://localphpsvr.com/demola/fetchdata/main.php';
//        $this->developer_key = 'AIzaSyCRNjROyNkZ2QmSoIkaXcJGsNoYbnJskYw';
//        $this->access_type = 'offline';

        $this->application_name = 'Reader Happiness Indicator';
        $this->client_id = '108350372048-l6qvnu9uf56u3j64noakj3qgoo4usaqf.apps.googleusercontent.com';
        $this->client_secret = 'EpAKLLeTSk6xUjJ0zvCk0PkS';
        $this->redirect_uri = 'http://demolavk02.mediacluster.fi/fetch-ga-data/main.php';
        $this->developer_key = 'AIzaSyCRNjROyNkZ2QmSoIkaXcJGsNoYbnJskYw';
        $this->access_type = 'offline';

        if (is_null($this->google_client)) {
            $this->google_client = new Google_Client();
            $this->google_client->setApplicationName($this->application_name);
            $this->google_client->setClientId($this->client_id);
            $this->google_client->setClientSecret($this->client_secret);
            $this->google_client->setRedirectUri($this->redirect_uri);
            $this->google_client->setDeveloperKey($this->developer_key);
            $this->google_client->setAccessType($this->access_type); //important
        }
        return $this->google_client;
    }

    public function getData($landing_page)
    {
        Yii::import('ext.googleapi.Google_Client', true);
        $token = $this->google_client->getAccessToken();
        $authObj = json_decode($token);

        $token = $this->getRefeshToken();
        $refreshToken = $token['token'];

        if (isset($authObj->refresh_token)) {
            $refreshToken = $authObj->refresh_token;
        }

        $tokenObj = new Token();

        if (strlen($refreshToken)) {
            $tokenObj->token = $refreshToken;
            $tokenObj->type = 'refresh';
            $tokenObj->save();
            $this->google_client->refreshToken($refreshToken);
        }
        $_SESSION['token'] = $this->google_client->getAccessToken();

        $today = strtotime("today 00:00");
        $yesterday = strtotime("-1 day", $today);

        $from = date('Y-m-d', $yesterday); // -1 days
        $to = date('Y-m-d', $today);

        $optDimensions = array(
            'ga:keyword'
        );

        $optMetrics = array(
            'ga:pageviews'
        );

        $metrics = implode(",", $optMetrics);
        $dimensions = implode(",", $optDimensions);

        //$metrics = 'ga:visits,ga:pageviewsPerVisit,ga:pageviews,ga:avgTimeOnPage,ga:bounces,ga:timeOnPage,ga:bounces,ga:visitors,ga:pageviews';
        //$dimensions = 'ga:landingPagePath,ga:pageTitle,ga:date,ga:year,ga:month,ga:day';

        $optParams = array(
            'dimensions' => $dimensions,
            'sort' => '-ga:pageviews',
            'filters' => 'ga:landingPagePath==' . base64_decode($landing_page),
            'max-results' => 150,
        );

        $data = $this->google_service->data_ga->get("ga:31405012", $from, $to, $metrics, $optParams);
        return $data;
    }

    public function getGoogleService()
    {
        Yii::import('ext.googleapi.Google_Client', true);
        Yii::import('ext.googleapi.contrib.Google_AnalyticsService', true);
        if (is_null($this->google_service)) {
            $google_client = $this->getGoogleClient();
            $this->google_service = new Google_AnalyticsService($google_client);
        }
        return $this->google_service;
    }

    public function getRefeshToken()
    {
        $token = Token::model()->find('type="refresh"');
        return $token;
    }

}